package com.acquisition.task.util;

import com.dcs.cn.common.constants.Constants;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * FTP工具
 *
 * @author wuqiwei
 * @date 2021/07/22
 */
public class FTPUtils {

    private static final Logger LOG = LoggerFactory.getLogger(FTPUtils.class);

    /**
     * 获取FTPClient
     *
     * @return FTPClient
     */
    public FTPClient getFTPClient() {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(Constants.FTP_IP, Constants.FTP_PORT);
            ftpClient.login(Constants.FTP_USER, Constants.FTP_PASSWORD);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                LOG.error("FTP连接失败，用户名或密码错误");
                ftpClient.disconnect();
            } else {
                LOG.info("FTP连接成功。");
            }
        } catch (IOException e) {
            e.printStackTrace();
            LOG.error("FTP异常信息：{}", e.toString());
        }
        return ftpClient;
    }

    /**
     * 上传文件
     *
     * @param ftpPath FTP服务器中文件所在路径
     * @param saveFileName 保存的ftp文件名称
     * @param inputStream 文件流
     * @return 成功返回true，否则返回false
     */
    public boolean uploadFile(String ftpPath, String saveFileName, InputStream inputStream) {
        boolean flag = false;
        FTPClient ftpClient = null;
        try {
            ftpClient = getFTPClient();
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return false;
            }
            if (!ftpClient.changeWorkingDirectory(ftpPath)) {
                ftpClient.makeDirectory(ftpPath);
                ftpClient.changeWorkingDirectory(ftpPath);
            }
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);
            ftpClient.storeFile(saveFileName, inputStream);
            inputStream.close();
            ftpClient.logout();
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

}
